package com.bosssoft.hr.train.j2se.example.file;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 云存储工具类
 * 提供和云存储相关的工具函数
 */
public class OssFileUtils {
    /**
     * 上传文件到存储桶
     *
     * @param file 要上传的文件对象
     */
    public static void upload(File file) {
        // 存储地址
        String endPoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 使用RAM用户，防止安全问题
        String accessKeyId = "LTAI5tA1D2YwhNFmS9F89qjQ";
        String accessKeySecret = "1RdqIrUheiQMgt8adMtx0cLmfLwSoJ";
        // 存储桶名
        String bucketName = "chufeng-official";
        // 目标路径
        String targetPath = "博思标识.png";
        // 文件内容
        FileInputStream fileInputStream = null;
        ByteArrayInputStream content = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            content = new ByteArrayInputStream(bytes);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }
        // 实例化云存储客户端对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {
            // 上传文件到存储桶
            ossClient.putObject(bucketName, targetPath, content);
            System.out.println("上传成功！");
        } catch (OSSException ossException) {
            ossException.printStackTrace();
        } finally {
            // 关闭连接
            ossClient.shutdown();
        }
    }
}
